package au.com.twosquared.animalfarm.sprites;

import au.com.twosquared.tools.Random;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;

/**
 * Creates, manages and draws animations given a list of images
 * 
 * @author Jan Martin <jan.martin@twosquared.com.au>
 * @version 1.0 2011-15-11
 * @since 2011-15-11
 * 
 */
public class Animation {

	/**
	 * A list of images creates frames
	 */
	private Image[] frames;
	/**
	 * The current frame of the animation
	 */
	private int frame;
	/**
	 * The time of the current frame
	 */
	private long time;
	/**
	 * The time interval between each frame
	 */
	private long interval;

	/**
	 * Creates an animation given a list of images and the time between each
	 * frame
	 * 
	 * @param frames
	 *            images used in animation
	 * @param interval
	 *            time interval between each frame
	 */
	public Animation(Image[] frames, long interval) {
		this.frames = frames;
		this.interval = interval;
		reset();
	}

	/**
	 * Updates the frames of the animation based on the change in time
	 * 
	 * @param delta
	 *            the change in time
	 */
	public void update(long delta) {
		time += delta;
		if (time > interval) {
			time = 0;
			frame++;
			if (frame > frames.length - 1) {
				frame = 0;
			}
		}
	}

	/**
	 * Set the animation to a random time and frame
	 */
	public void randomize() {
		time = Random.integer(0, (int) interval);
		frame = Random.integer(0, frames.length);
	}

	/**
	 * Reset the animation to the first frame, restart timer as well
	 */
	public void reset() {
		time = 0;
		frame = 0;
	}

	/**
	 * Draws a sprite onto a given x, y position
	 * 
	 * @param batch
	 *            the sprite
	 * @param x
	 *            the x position
	 * @param y
	 *            the y position
	 */
	public void draw(SpriteBatch batch, float x, float y) {
		batch.draw(frames[frame].image(), x, y);
	}
}
